package cn.tedu.springmvc2.controller;

import cn.tedu.springmvc2.mapper.UserMapper;
import cn.tedu.springmvc2.pojo.dto.UserDTO;
import cn.tedu.springmvc2.pojo.entity.User;
import cn.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//RESTful编码规则
@RestController//是 @Controller 和 @ResponseBody 的组合注解，主要用于构建 RESTful Web 服务
/*
标记一个类为控制器，类似于 @Controller。
自动将控制器中的方法返回值转换为 HTTP 响应体，类似于 @ResponseBody
 */
@RequestMapping("/users")//Request(浏览器发送的)//将http请求映射到处理方法上
public class RESTfulUserController {
    @Autowired
    private UserMapper userMapper;
//    @RequestMapping(value = "/users",method = RequestMethod.POST)
//    @PostMapping("/users")
    @PostMapping
    public String add(UserDTO  userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        int num = userMapper.insert(user);
        return num>0?"添加成功":"添加失败";

    }
//    @RequestMapping (value = "/users",method = RequestMethod.PUT)
//    @PutMapping("/users")
    @PutMapping
    public String update(UserDTO userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        int num = userMapper.updateByUsername(user);
        return num>0?"修改成功":"修改失败";
    }
//    @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
//    @DeleteMapping("/users/{id}")
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("删除用户,id为:"+id);
        int num = userMapper.deleteById(id);
        return num>0?"删除成功":"删除失败";
    }

//    @RequestMapping(value = "/users",method = RequestMethod.GET)
//    @GetMapping("/users")
    @GetMapping
    public List<UserVO> findAll(){
        return userMapper.findAll();
    }

//    @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
//    @GetMapping("/users/{id}")
    @GetMapping("/{id}")
    public UserVO find(@PathVariable Integer id){
        return userMapper.findById(id);
    }

}
